package com.atguigu.krp.handler;

import com.atguigu.krp.common.protocol.ProxyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @Description  将外网请求转发到内网客户端的 handler
 * @author KEIO  on 2022/1/12.
 * @version 1.0
 */
@Slf4j
@Component
public class RemoteHandler extends ChannelInboundHandlerAdapter {


    private int remotePort;

    @Autowired
    private ServerHandler serverHandler;

    /*
    连接初始化
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        send(ProxyMessage.TYPE_CONNECTED, ctx.channel().id().asLongText(), null);
        log.info("端口: {} 有请求进入, channelId为{}", remotePort, ctx.channel().id().asLongText());

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        send(ProxyMessage.TYPE_DISCONNECTED, ctx.channel().id().asLongText(), null);
        log.info("端口：{} 有请求离开， channelId为{}", remotePort, ctx.channel().id().asLongText());
    }

    /*
    读取到 从公网发出的数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        byte[] data = (byte[]) msg;
        send(ProxyMessage.TYPE_DATA, ctx.channel().id().asLongText(), data);
        log.info("{} 端口有数据发送, channelId为{}", remotePort, ctx.channel().id().asLongText());
    }


    /**
     * 将外网的请求转发到内网的客户端
     */
    private void send(int type, String channelId, byte[] data) {

    }




}
